# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def print(self, level):
        prefix = " " * level
        return "{}{}\n".format(prefix, self.val) + (self.left.print(level+1) if self.left else "") + (self.right.print(level+1) if self.right else "")

    def __str__(self):
        return self.print(0)

    def __rper__(self):
        return self.print(0)
        

class Solution(object):
    def buildTree(self, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        indexDict = {}
        for i in range(len(inorder)):
            indexDict.update({inorder[i]:i})
        def build(ibegin, iend, pbegin, pend):
            if ibegin>iend:
                return None
            node = TreeNode(postorder[pend])
            if ibegin==iend:
                return node
            i = indexDict[postorder[pend]]
            leftLen = i-ibegin
            node.left = build(ibegin, ibegin+leftLen-1, pbegin, pbegin+leftLen-1)
            rightLen = iend-i
            node.right = build(iend-rightLen+1, iend, pend-rightLen, pend-1)
            return node

        return build(0, len(inorder)-1, 0, len(inorder)-1)

print(Solution().buildTree([1,3,2], [3,2,1]))